← Index
NYTProf Performance Profile   
For starman worker -M FindBin --max-requests 50 --workers 2 --user=kohadev-koha --group kohadev-koha --pid /var/run/koha/kohadev/plack.pid --daemonize --access-log /var/log/koha/kohadev/plack.log --error-log /var/log/koha/kohadev/plack-error.log -E deployment --socket /var/run/koha/kohadev/plack.sock /etc/koha/sites/kohadev/plack.psgi
  Run on Fri Jan 8 14:31:06 2016
Reported on Fri Jan 8 14:31:36 2016

Filename(eval 167)[/usr/share/perl5/JSON.pm:268]
StatementsExecuted 20 statements in 1.26ms
Eval Invoked At/usr/share/perl5/JSON.pm line 268
Subroutines
Calls P F Exclusive
Time
Inclusive
Time
Subroutine
11119µs19µsJSON::Backend::XS::::init JSON::Backend::XS::init
11117µs51µsJSON::Backend::XS::::BEGIN@9 JSON::Backend::XS::BEGIN@9
11111µs30µsJSON::Backend::XS::::BEGIN@11 JSON::Backend::XS::BEGIN@11
11111µs17µsJSON::Backend::XS::Supportable::::BEGIN@99JSON::Backend::XS::Supportable::BEGIN@99
11111µs16µsJSON::Backend::XS::::BEGIN@42 JSON::Backend::XS::BEGIN@42
11110µs28µsJSON::Backend::XS::::BEGIN@18 JSON::Backend::XS::BEGIN@18
11110µs18µsJSON::Backend::XS::::BEGIN@29 JSON::Backend::XS::BEGIN@29
0000s0sJSON::Backend::XS::Supportable::::__ANON__[:110]JSON::Backend::XS::Supportable::__ANON__[:110]
0000s0sJSON::Backend::XS::Supportable::::__ANON__[:114]JSON::Backend::XS::Supportable::__ANON__[:114]
0000s0sJSON::Backend::XS::Supportable::::_decodeJSON::Backend::XS::Supportable::_decode
0000s0sJSON::Backend::XS::Supportable::::_encodeJSON::Backend::XS::Supportable::_encode
0000s0sJSON::Backend::XS::Supportable::::_incr_parseJSON::Backend::XS::Supportable::_incr_parse
0000s0sJSON::Backend::XS::Supportable::::_make_unsupported_methodJSON::Backend::XS::Supportable::_make_unsupported_method
0000s0sJSON::Backend::XS::Supportable::::_set_for_ppJSON::Backend::XS::Supportable::_set_for_pp
0000s0sJSON::Backend::XS::Supportable::::decode_prefixJSON::Backend::XS::Supportable::decode_prefix
0000s0sJSON::Backend::XS::Supportable::::get_indent_lengthJSON::Backend::XS::Supportable::get_indent_length
0000s0sJSON::Backend::XS::Supportable::::indent_lengthJSON::Backend::XS::Supportable::indent_length
0000s0sJSON::Backend::XS::::__ANON__[:32] JSON::Backend::XS::__ANON__[:32]
0000s0sJSON::Backend::XS::::__ANON__[:33] JSON::Backend::XS::__ANON__[:33]
0000s0sJSON::Backend::XS::::__ANON__[:63] JSON::Backend::XS::__ANON__[:63]
0000s0sJSON::Backend::XS::::support_by_pp JSON::Backend::XS::support_by_pp
Call graph for these subroutines as a Graphviz dot language file.
Line State
ments
Time
on line
Calls Time
in subs
Code
1
2
3#
4# Helper classes for Backend Module (XS)
5#
6
7package JSON::Backend::XS;
8
9284µs285µs
# spent 51µs (17+34) within JSON::Backend::XS::BEGIN@9 which was called: # once (17µs+34µs) by JSON::_load_xs at line 9
use constant INDENT_LENGTH_FLAG => 15 << 12;
# spent 51µs making 1 call to JSON::Backend::XS::BEGIN@9 # spent 34µs making 1 call to constant::import
10
11129µs119µs
# spent 30µs (11+19) within JSON::Backend::XS::BEGIN@11 which was called: # once (11µs+19µs) by JSON::_load_xs at line 16
use constant UNSUPPORTED_ENCODE_FLAG => {
# spent 19µs making 1 call to constant::import
12 ESCAPE_SLASH => 0x00000010,
13 ALLOW_BIGNUM => 0x00000020,
14 AS_NONBLESSED => 0x00000040,
15 EXPANDED => 0x10000000, # for developer's
16131µs130µs};
# spent 30µs making 1 call to JSON::Backend::XS::BEGIN@11
17
18127µs118µs
# spent 28µs (10+18) within JSON::Backend::XS::BEGIN@18 which was called: # once (10µs+18µs) by JSON::_load_xs at line 24
use constant UNSUPPORTED_DECODE_FLAG => {
# spent 18µs making 1 call to constant::import
19 LOOSE => 0x00000001,
20 ALLOW_BIGNUM => 0x00000002,
21 ALLOW_BAREKEY => 0x00000004,
22 ALLOW_SINGLEQUOTE => 0x00000008,
23 EXPANDED => 0x20000000, # for developer's
24140µs128µs};
# spent 28µs making 1 call to JSON::Backend::XS::BEGIN@18
25
26
27
# spent 19µs within JSON::Backend::XS::init which was called: # once (19µs+0s) by JSON::_load_xs at line 269 of JSON.pm
sub init {
2812µs local $^W;
292133µs226µs
# spent 18µs (10+8) within JSON::Backend::XS::BEGIN@29 which was called: # once (10µs+8µs) by JSON::_load_xs at line 29
no strict qw(refs);
# spent 18µs making 1 call to JSON::Backend::XS::BEGIN@29 # spent 8µs making 1 call to strict::unimport
3013µs *{"JSON::decode_json"} = \&{"JSON::XS::decode_json"};
3112µs *{"JSON::encode_json"} = \&{"JSON::XS::encode_json"};
3215µs *{"JSON::XS::is_xs"} = sub { 1 };
3316µs *{"JSON::XS::is_pp"} = sub { 0 };
3415µs return 1;
35}
36
37
38sub support_by_pp {
39 my ($class, @methods) = @_;
40
41 local $^W;
422351µs221µs
# spent 16µs (11+5) within JSON::Backend::XS::BEGIN@42 which was called: # once (11µs+5µs) by JSON::_load_xs at line 42
no strict qw(refs);
# spent 16µs making 1 call to JSON::Backend::XS::BEGIN@42 # spent 5µs making 1 call to strict::unimport
43
44 my $JSON_XS_encode_orignal = \&JSON::XS::encode;
45 my $JSON_XS_decode_orignal = \&JSON::XS::decode;
46 my $JSON_XS_incr_parse_orignal = \&JSON::XS::incr_parse;
47
48 *JSON::XS::decode = \&JSON::Backend::XS::Supportable::_decode;
49 *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
50 *JSON::XS::incr_parse = \&JSON::Backend::XS::Supportable::_incr_parse;
51
52 *{JSON::XS::_original_decode} = $JSON_XS_decode_orignal;
53 *{JSON::XS::_original_encode} = $JSON_XS_encode_orignal;
54 *{JSON::XS::_original_incr_parse} = $JSON_XS_incr_parse_orignal;
55
56 push @JSON::Backend::XS::Supportable::ISA, 'JSON';
57
58 my $pkg = 'JSON::Backend::XS::Supportable';
59
60 *{JSON::new} = sub {
61 my $proto = JSON::XS->new; $$proto = 0;
62 bless $proto, $pkg;
63 };
64
65
66 for my $method (@methods) {
67 my $flag = uc($method);
68 my $type |= (UNSUPPORTED_ENCODE_FLAG->{$flag} || 0);
69 $type |= (UNSUPPORTED_DECODE_FLAG->{$flag} || 0);
70
71 next unless($type);
72
73 $pkg->_make_unsupported_method($method => $type);
74 }
75
76 push @{"JSON::XS::Boolean::ISA"}, qw(JSON::PP::Boolean);
77 push @{"JSON::PP::Boolean::ISA"}, qw(JSON::Boolean);
78
79 $JSON::DEBUG and Carp::carp("set -support_by_pp mode.");
80
81 return 1;
82}
83
- -
87#
88# Helper classes for XS
89#
90
91package JSON::Backend::XS::Supportable;
92
9313µs$Carp::Internal{'JSON::Backend::XS::Supportable'} = 1;
94
95sub _make_unsupported_method {
96 my ($pkg, $method, $type) = @_;
97
98 local $^W;
992536µs223µs
# spent 17µs (11+6) within JSON::Backend::XS::Supportable::BEGIN@99 which was called: # once (11µs+6µs) by JSON::_load_xs at line 99
no strict qw(refs);
# spent 17µs making 1 call to JSON::Backend::XS::Supportable::BEGIN@99 # spent 6µs making 1 call to strict::unimport
100
101 *{"$pkg\::$method"} = sub {
102 local $^W;
103 if (defined $_[1] ? $_[1] : 1) {
104 ${$_[0]} |= $type;
105 }
106 else {
107 ${$_[0]} &= ~$type;
108 }
109 $_[0];
110 };
111
112 *{"$pkg\::get_$method"} = sub {
113 ${$_[0]} & $type ? 1 : '';
114 };
115
116}
117
118
119sub _set_for_pp {
120 JSON::_load_pp( $_INSTALL_ONLY );
121
122 my $type = shift;
123 my $pp = JSON::PP->new;
124 my $prop = $_[0]->property;
125
126 for my $name (keys %$prop) {
127 $pp->$name( $prop->{$name} ? $prop->{$name} : 0 );
128 }
129
130 my $unsupported = $type eq 'encode' ? JSON::Backend::XS::UNSUPPORTED_ENCODE_FLAG
131 : JSON::Backend::XS::UNSUPPORTED_DECODE_FLAG;
132 my $flags = ${$_[0]} || 0;
133
134 for my $name (keys %$unsupported) {
135 next if ($name eq 'EXPANDED'); # for developer's
136 my $enable = ($flags & $unsupported->{$name}) ? 1 : 0;
137 my $method = lc $name;
138 $pp->$method($enable);
139 }
140
141 $pp->indent_length( $_[0]->get_indent_length );
142
143 return $pp;
144}
145
146sub _encode { # using with PP encode
147 if (${$_[0]}) {
148 _set_for_pp('encode' => @_)->encode($_[1]);
149 }
150 else {
151 $_[0]->_original_encode( $_[1] );
152 }
153}
154
155
156sub _decode { # if unsupported-flag is set, use PP
157 if (${$_[0]}) {
158 _set_for_pp('decode' => @_)->decode($_[1]);
159 }
160 else {
161 $_[0]->_original_decode( $_[1] );
162 }
163}
164
165
166sub decode_prefix { # if unsupported-flag is set, use PP
167 _set_for_pp('decode' => @_)->decode_prefix($_[1]);
168}
169
170
171sub _incr_parse {
172 if (${$_[0]}) {
173 _set_for_pp('decode' => @_)->incr_parse($_[1]);
174 }
175 else {
176 $_[0]->_original_incr_parse( $_[1] );
177 }
178}
179
180
181sub get_indent_length {
182 ${$_[0]} << 4 >> 16;
183}
184
185
186sub indent_length {
187 my $length = $_[1];
188
189 if (!defined $length or $length > 15 or $length < 0) {
190 Carp::carp "The acceptable range of indent_length() is 0 to 15.";
191 }
192 else {
193 local $^W;
194 $length <<= 12;
195 ${$_[0]} &= ~ JSON::Backend::XS::INDENT_LENGTH_FLAG;
196 ${$_[0]} |= $length;
197 *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
198 }
199
200 $_[0];
201}
202
203
20414µs1;
205__END__
206
207=head1 NAME
208
209JSON - JSON (JavaScript Object Notation) encoder/decoder
210
211=head1 SYNOPSIS
212
213 use JSON; # imports encode_json, decode_json, to_json and from_json.
214
215 # simple and fast interfaces (expect/generate UTF-8)
216
217 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
218 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
219
220 # OO-interface
221
222 $json = JSON->new->allow_nonref;
223
224 $json_text = $json->encode( $perl_scalar );
225 $perl_scalar = $json->decode( $json_text );
226
227 $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
228
229 # If you want to use PP only support features, call with '-support_by_pp'
230 # When XS unsupported feature is enable, using PP (de|en)code instead of XS ones.
231
232 use JSON -support_by_pp;
233
234 # option-acceptable interfaces (expect/generate UNICODE by default)
235
236 $json_text = to_json( $perl_scalar, { ascii => 1, pretty => 1 } );
237 $perl_scalar = from_json( $json_text, { utf8 => 1 } );
238
239 # Between (en|de)code_json and (to|from)_json, if you want to write
240 # a code which communicates to an outer world (encoded in UTF-8),
241 # recommend to use (en|de)code_json.
242
243=head1 VERSION
244
245 2.59
246
247This version is compatible with JSON::XS B<2.34> and later.
248
249
250=head1 NOTE
251
252JSON::PP was earlier included in the C<JSON> distribution, but
253has since Perl 5.14 been a core module. For this reason,
254L<JSON::PP> was removed from the JSON distribution and can now
255be found also in the Perl5 repository at
256
257=over
258
259=item * L<http://perl5.git.perl.org/perl.git>
260
261=back
262
263(The newest JSON::PP version still exists in CPAN.)
264
265Instead, the C<JSON> distribution will include JSON::backportPP
266for backwards computability. JSON.pm should thus work as it did
267before.
268
269=head1 DESCRIPTION
270
271 ************************** CAUTION ********************************
272 * This is 'JSON module version 2' and there are many differences *
273 * to version 1.xx *
274 * Please check your applications using old version. *
275 * See to 'INCOMPATIBLE CHANGES TO OLD VERSION' *
276 *******************************************************************
277
278JSON (JavaScript Object Notation) is a simple data format.
279See to L<http://www.json.org/> and C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>).
280
281This module converts Perl data structures to JSON and vice versa using either
282L<JSON::XS> or L<JSON::PP>.
283
284JSON::XS is the fastest and most proper JSON module on CPAN which must be
285compiled and installed in your environment.
286JSON::PP is a pure-Perl module which is bundled in this distribution and
287has a strong compatibility to JSON::XS.
288
289This module try to use JSON::XS by default and fail to it, use JSON::PP instead.
290So its features completely depend on JSON::XS or JSON::PP.
291
292See to L<BACKEND MODULE DECISION>.
293
294To distinguish the module name 'JSON' and the format type JSON,
295the former is quoted by CE<lt>E<gt> (its results vary with your using media),
296and the latter is left just as it is.
297
298Module name : C<JSON>
299
300Format type : JSON
301
302=head2 FEATURES
303
304=over
305
306=item * correct unicode handling
307
308This module (i.e. backend modules) knows how to handle Unicode, documents
309how and when it does so, and even documents what "correct" means.
310
311Even though there are limitations, this feature is available since Perl version 5.6.
312
313JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions
314C<JSON> should call JSON::PP as the backend which can be used since Perl 5.005.
315
316With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem,
317JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available.
318See to L<JSON::PP/UNICODE HANDLING ON PERLS> for more information.
319
320See also to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>
321and L<JSON::XS/ENCODING/CODESET_FLAG_NOTES>.
322
323
324=item * round-trip integrity
325
326When you serialise a perl data structure using only data types supported
327by JSON and Perl, the deserialised data structure is identical on the Perl
328level. (e.g. the string "2.0" doesn't suddenly become "2" just because
329it looks like a number). There I<are> minor exceptions to this, read the
330L</MAPPING> section below to learn about those.
331
332
333=item * strict checking of JSON correctness
334
335There is no guessing, no generating of illegal JSON texts by default,
336and only JSON is accepted as input by default (the latter is a security
337feature).
338
339See to L<JSON::XS/FEATURES> and L<JSON::PP/FEATURES>.
340
341=item * fast
342
343This module returns a JSON::XS object itself if available.
344Compared to other JSON modules and other serialisers such as Storable,
345JSON::XS usually compares favorably in terms of speed, too.
346
347If not available, C<JSON> returns a JSON::PP object instead of JSON::XS and
348it is very slow as pure-Perl.
349
350=item * simple to use
351
352This module has both a simple functional interface as well as an
353object oriented interface interface.
354
355=item * reasonably versatile output formats
356
357You can choose between the most compact guaranteed-single-line format possible
358(nice for simple line-based protocols), a pure-ASCII format (for when your transport
359is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed
360format (for when you want to read that stuff). Or you can combine those features
361in whatever way you like.
362
363=back
364
365=head1 FUNCTIONAL INTERFACE
366
367Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
368C<to_json> and C<from_json> are additional functions.
369
370=head2 encode_json
371
372 $json_text = encode_json $perl_scalar
373
374Converts the given Perl data structure to a UTF-8 encoded, binary string.
375
376This function call is functionally identical to:
377
378 $json_text = JSON->new->utf8->encode($perl_scalar)
379
380=head2 decode_json
381
382 $perl_scalar = decode_json $json_text
383
384The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
385to parse that as an UTF-8 encoded JSON text, returning the resulting
386reference.
387
388This function call is functionally identical to:
389
390 $perl_scalar = JSON->new->utf8->decode($json_text)
391
392
393=head2 to_json
394
395 $json_text = to_json($perl_scalar)
396
397Converts the given Perl data structure to a json string.
398
399This function call is functionally identical to:
400
401 $json_text = JSON->new->encode($perl_scalar)
402
403Takes a hash reference as the second.
404
405 $json_text = to_json($perl_scalar, $flag_hashref)
406
407So,
408
409 $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1})
410
411equivalent to:
412
413 $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
414
415If you want to write a modern perl code which communicates to outer world,
416you should use C<encode_json> (supposed that JSON data are encoded in UTF-8).
417
418=head2 from_json
419
420 $perl_scalar = from_json($json_text)
421
422The opposite of C<to_json>: expects a json string and tries
423to parse it, returning the resulting reference.
424
425This function call is functionally identical to:
426
427 $perl_scalar = JSON->decode($json_text)
428
429Takes a hash reference as the second.
430
431 $perl_scalar = from_json($json_text, $flag_hashref)
432
433So,
434
435 $perl_scalar = from_json($json_text, {utf8 => 1})
436
437equivalent to:
438
439 $perl_scalar = JSON->new->utf8(1)->decode($json_text)
440
441If you want to write a modern perl code which communicates to outer world,
442you should use C<decode_json> (supposed that JSON data are encoded in UTF-8).
443
444=head2 JSON::is_bool
445
446 $is_boolean = JSON::is_bool($scalar)
447
448Returns true if the passed scalar represents either JSON::true or
449JSON::false, two constants that act like C<1> and C<0> respectively
450and are also used to represent JSON C<true> and C<false> in Perl strings.
451
452=head2 JSON::true
453
454Returns JSON true value which is blessed object.
455It C<isa> JSON::Boolean object.
456
457=head2 JSON::false
458
459Returns JSON false value which is blessed object.
460It C<isa> JSON::Boolean object.
461
462=head2 JSON::null
463
464Returns C<undef>.
465
466See L<MAPPING>, below, for more information on how JSON values are mapped to
467Perl.
468
469=head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
470
471This section supposes that your perl version is 5.8 or later.
472
473If you know a JSON text from an outer world - a network, a file content, and so on,
474is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
475with C<utf8> enable. And the decoded result will contain UNICODE characters.
476
477 # from network
478 my $json = JSON->new->utf8;
479 my $json_text = CGI->new->param( 'json_data' );
480 my $perl_scalar = $json->decode( $json_text );
481
482 # from file content
483 local $/;
484 open( my $fh, '<', 'json.data' );
485 $json_text = <$fh>;
486 $perl_scalar = decode_json( $json_text );
487
488If an outer data is not encoded in UTF-8, firstly you should C<decode> it.
489
490 use Encode;
491 local $/;
492 open( my $fh, '<', 'json.data' );
493 my $encoding = 'cp932';
494 my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
495
496 # or you can write the below code.
497 #
498 # open( my $fh, "<:encoding($encoding)", 'json.data' );
499 # $unicode_json_text = <$fh>;
500
501In this case, C<$unicode_json_text> is of course UNICODE string.
502So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
503Instead of them, you use C<JSON> module object with C<utf8> disable or C<from_json>.
504
505 $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
506 # or
507 $perl_scalar = from_json( $unicode_json_text );
508
509Or C<encode 'utf8'> and C<decode_json>:
510
511 $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
512 # this way is not efficient.
513
514And now, you want to convert your C<$perl_scalar> into JSON data and
515send it to an outer world - a network or a file content, and so on.
516
517Your data usually contains UNICODE strings and you want the converted data to be encoded
518in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable.
519
520 print encode_json( $perl_scalar ); # to a network? file? or display?
521 # or
522 print $json->utf8->encode( $perl_scalar );
523
524If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
525for some reason, then its characters are regarded as B<latin1> for perl
526(because it does not concern with your $encoding).
527You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
528Instead of them, you use C<JSON> module object with C<utf8> disable or C<to_json>.
529Note that the resulted text is a UNICODE string but no problem to print it.
530
531 # $perl_scalar contains $encoding encoded string values
532 $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
533 # or
534 $unicode_json_text = to_json( $perl_scalar );
535 # $unicode_json_text consists of characters less than 0x100
536 print $unicode_json_text;
537
538Or C<decode $encoding> all string values and C<encode_json>:
539
540 $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
541 # ... do it to each string values, then encode_json
542 $json_text = encode_json( $perl_scalar );
543
544This method is a proper way but probably not efficient.
545
546See to L<Encode>, L<perluniintro>.
547
548
549=head1 COMMON OBJECT-ORIENTED INTERFACE
550
551=head2 new
552
553 $json = JSON->new
554
555Returns a new C<JSON> object inherited from either JSON::XS or JSON::PP
556that can be used to de/encode JSON strings.
557
558All boolean flags described below are by default I<disabled>.
559
560The mutators for flags all return the JSON object again and thus calls can
561be chained:
562
563 my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
564 => {"a": [1, 2]}
565
566=head2 ascii
567
568 $json = $json->ascii([$enable])
569
570 $enabled = $json->get_ascii
571
572If $enable is true (or missing), then the encode method will not generate characters outside
573the code range 0..127. Any Unicode characters outside that range will be escaped using either
574a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
575
576If $enable is false, then the encode method will not escape Unicode characters unless
577required by the JSON syntax or other flags. This results in a faster and more compact format.
578
579This feature depends on the used Perl version and environment.
580
581See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
582
583 JSON->new->ascii(1)->encode([chr 0x10401])
584 => ["\ud801\udc01"]
585
586=head2 latin1
587
588 $json = $json->latin1([$enable])
589
590 $enabled = $json->get_latin1
591
592If $enable is true (or missing), then the encode method will encode the resulting JSON
593text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
594
595If $enable is false, then the encode method will not escape Unicode characters
596unless required by the JSON syntax or other flags.
597
598 JSON->new->latin1->encode (["\x{89}\x{abc}"]
599 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
600
601=head2 utf8
602
603 $json = $json->utf8([$enable])
604
605 $enabled = $json->get_utf8
606
607If $enable is true (or missing), then the encode method will encode the JSON result
608into UTF-8, as required by many protocols, while the decode method expects to be handled
609an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
610characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
611
612In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
613encoding families, as described in RFC4627.
614
615If $enable is false, then the encode method will return the JSON string as a (non-encoded)
616Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
617(e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
618
619
620Example, output UTF-16BE-encoded JSON:
621
622 use Encode;
623 $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
624
625Example, decode UTF-32LE-encoded JSON:
626
627 use Encode;
628 $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
629
630See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
631
632
633=head2 pretty
634
635 $json = $json->pretty([$enable])
636
637This enables (or disables) all of the C<indent>, C<space_before> and
638C<space_after> (and in the future possibly more) flags in one call to
639generate the most readable (or most compact) form possible.
640
641Equivalent to:
642
643 $json->indent->space_before->space_after
644
645The indent space length is three and JSON::XS cannot change the indent
646space length.
647
648=head2 indent
649
650 $json = $json->indent([$enable])
651
652 $enabled = $json->get_indent
653
654If C<$enable> is true (or missing), then the C<encode> method will use a multiline
655format as output, putting every array member or object/hash key-value pair
656into its own line, identifying them properly.
657
658If C<$enable> is false, no newlines or indenting will be produced, and the
659resulting JSON text is guaranteed not to contain any C<newlines>.
660
661This setting has no effect when decoding JSON texts.
662
663The indent space length is three.
664With JSON::PP, you can also access C<indent_length> to change indent space length.
665
666
667=head2 space_before
668
669 $json = $json->space_before([$enable])
670
671 $enabled = $json->get_space_before
672
673If C<$enable> is true (or missing), then the C<encode> method will add an extra
674optional space before the C<:> separating keys from values in JSON objects.
675
676If C<$enable> is false, then the C<encode> method will not add any extra
677space at those places.
678
679This setting has no effect when decoding JSON texts.
680
681Example, space_before enabled, space_after and indent disabled:
682
683 {"key" :"value"}
684
685
686=head2 space_after
687
688 $json = $json->space_after([$enable])
689
690 $enabled = $json->get_space_after
691
692If C<$enable> is true (or missing), then the C<encode> method will add an extra
693optional space after the C<:> separating keys from values in JSON objects
694and extra whitespace after the C<,> separating key-value pairs and array
695members.
696
697If C<$enable> is false, then the C<encode> method will not add any extra
698space at those places.
699
700This setting has no effect when decoding JSON texts.
701
702Example, space_before and indent disabled, space_after enabled:
703
704 {"key": "value"}
705
706
707=head2 relaxed
708
709 $json = $json->relaxed([$enable])
710
711 $enabled = $json->get_relaxed
712
713If C<$enable> is true (or missing), then C<decode> will accept some
714extensions to normal JSON syntax (see below). C<encode> will not be
715affected in anyway. I<Be aware that this option makes you accept invalid
716JSON texts as if they were valid!>. I suggest only to use this option to
717parse application-specific files written by humans (configuration files,
718resource files etc.)
719
720If C<$enable> is false (the default), then C<decode> will only accept
721valid JSON texts.
722
723Currently accepted extensions are:
724
725=over 4
726
727=item * list items can have an end-comma
728
729JSON I<separates> array elements and key-value pairs with commas. This
730can be annoying if you write JSON texts manually and want to be able to
731quickly append elements, so this extension accepts comma at the end of
732such items not just between them:
733
734 [
735 1,
736 2, <- this comma not normally allowed
737 ]
738 {
739 "k1": "v1",
740 "k2": "v2", <- this comma not normally allowed
741 }
742
743=item * shell-style '#'-comments
744
745Whenever JSON allows whitespace, shell-style comments are additionally
746allowed. They are terminated by the first carriage-return or line-feed
747character, after which more white-space and comments are allowed.
748
749 [
750 1, # this comment not allowed in JSON
751 # neither this one...
752 ]
753
754=back
755
756
757=head2 canonical
758
759 $json = $json->canonical([$enable])
760
761 $enabled = $json->get_canonical
762
763If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
764by sorting their keys. This is adding a comparatively high overhead.
765
766If C<$enable> is false, then the C<encode> method will output key-value
767pairs in the order Perl stores them (which will likely change between runs
768of the same script).
769
770This option is useful if you want the same data structure to be encoded as
771the same JSON text (given the same overall settings). If it is disabled,
772the same hash might be encoded differently even if contains the same data,
773as key-value pairs have no inherent ordering in Perl.
774
775This setting has no effect when decoding JSON texts.
776
777=head2 allow_nonref
778
779 $json = $json->allow_nonref([$enable])
780
781 $enabled = $json->get_allow_nonref
782
783If C<$enable> is true (or missing), then the C<encode> method can convert a
784non-reference into its corresponding string, number or null JSON value,
785which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
786values instead of croaking.
787
788If C<$enable> is false, then the C<encode> method will croak if it isn't
789passed an arrayref or hashref, as JSON texts must either be an object
790or array. Likewise, C<decode> will croak if given something that is not a
791JSON object or array.
792
793 JSON->new->allow_nonref->encode ("Hello, World!")
794 => "Hello, World!"
795
796=head2 allow_unknown
797
798 $json = $json->allow_unknown ([$enable])
799
800 $enabled = $json->get_allow_unknown
801
802If $enable is true (or missing), then "encode" will *not* throw an
803exception when it encounters values it cannot represent in JSON (for
804example, filehandles) but instead will encode a JSON "null" value.
805Note that blessed objects are not included here and are handled
806separately by c<allow_nonref>.
807
808If $enable is false (the default), then "encode" will throw an
809exception when it encounters anything it cannot encode as JSON.
810
811This option does not affect "decode" in any way, and it is
812recommended to leave it off unless you know your communications
813partner.
814
815=head2 allow_blessed
816
817 $json = $json->allow_blessed([$enable])
818
819 $enabled = $json->get_allow_blessed
820
821If C<$enable> is true (or missing), then the C<encode> method will not
822barf when it encounters a blessed reference. Instead, the value of the
823B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
824disabled or no C<TO_JSON> method found) or a representation of the
825object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
826encoded. Has no effect on C<decode>.
827
828If C<$enable> is false (the default), then C<encode> will throw an
829exception when it encounters a blessed object.
830
831
832=head2 convert_blessed
833
834 $json = $json->convert_blessed([$enable])
835
836 $enabled = $json->get_convert_blessed
837
838If C<$enable> is true (or missing), then C<encode>, upon encountering a
839blessed object, will check for the availability of the C<TO_JSON> method
840on the object's class. If found, it will be called in scalar context
841and the resulting scalar will be encoded instead of the object. If no
842C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
843to do.
844
845The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
846returns other blessed objects, those will be handled in the same
847way. C<TO_JSON> must take care of not causing an endless recursion cycle
848(== crash) in this case. The name of C<TO_JSON> was chosen because other
849methods called by the Perl core (== not by the user of the object) are
850usually in upper case letters and to avoid collisions with the C<to_json>
851function or method.
852
853This setting does not yet influence C<decode> in any way.
854
855If C<$enable> is false, then the C<allow_blessed> setting will decide what
856to do when a blessed object is found.
857
858=over
859
860=item convert_blessed_universally mode
861
862If use C<JSON> with C<-convert_blessed_universally>, the C<UNIVERSAL::TO_JSON>
863subroutine is defined as the below code:
864
865 *UNIVERSAL::TO_JSON = sub {
866 my $b_obj = B::svref_2object( $_[0] );
867 return $b_obj->isa('B::HV') ? { %{ $_[0] } }
868 : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
869 : undef
870 ;
871 }
872
873This will cause that C<encode> method converts simple blessed objects into
874JSON objects as non-blessed object.
875
876 JSON -convert_blessed_universally;
877 $json->allow_blessed->convert_blessed->encode( $blessed_object )
878
879This feature is experimental and may be removed in the future.
880
881=back
882
883=head2 filter_json_object
884
885 $json = $json->filter_json_object([$coderef])
886
887When C<$coderef> is specified, it will be called from C<decode> each
888time it decodes a JSON object. The only argument passed to the coderef
889is a reference to the newly-created hash. If the code references returns
890a single scalar (which need not be a reference), this value
891(i.e. a copy of that scalar to avoid aliasing) is inserted into the
892deserialised data structure. If it returns an empty list
893(NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
894hash will be inserted. This setting can slow down decoding considerably.
895
896When C<$coderef> is omitted or undefined, any existing callback will
897be removed and C<decode> will not change the deserialised hash in any
898way.
899
900Example, convert all JSON objects into the integer 5:
901
902 my $js = JSON->new->filter_json_object (sub { 5 });
903 # returns [5]
904 $js->decode ('[{}]'); # the given subroutine takes a hash reference.
905 # throw an exception because allow_nonref is not enabled
906 # so a lone 5 is not allowed.
907 $js->decode ('{"a":1, "b":2}');
908
909
910=head2 filter_json_single_key_object
911
912 $json = $json->filter_json_single_key_object($key [=> $coderef])
913
914Works remotely similar to C<filter_json_object>, but is only called for
915JSON objects having a single key named C<$key>.
916
917This C<$coderef> is called before the one specified via
918C<filter_json_object>, if any. It gets passed the single value in the JSON
919object. If it returns a single value, it will be inserted into the data
920structure. If it returns nothing (not even C<undef> but the empty list),
921the callback from C<filter_json_object> will be called next, as if no
922single-key callback were specified.
923
924If C<$coderef> is omitted or undefined, the corresponding callback will be
925disabled. There can only ever be one callback for a given key.
926
927As this callback gets called less often then the C<filter_json_object>
928one, decoding speed will not usually suffer as much. Therefore, single-key
929objects make excellent targets to serialise Perl objects into, especially
930as single-key JSON objects are as close to the type-tagged value concept
931as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
932support this in any way, so you need to make sure your data never looks
933like a serialised Perl hash.
934
935Typical names for the single object key are C<__class_whatever__>, or
936C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
937things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
938with real hashes.
939
940Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
941into the corresponding C<< $WIDGET{<id>} >> object:
942
943 # return whatever is in $WIDGET{5}:
944 JSON
945 ->new
946 ->filter_json_single_key_object (__widget__ => sub {
947 $WIDGET{ $_[0] }
948 })
949 ->decode ('{"__widget__": 5')
950
951 # this can be used with a TO_JSON method in some "widget" class
952 # for serialisation to json:
953 sub WidgetBase::TO_JSON {
954 my ($self) = @_;
955
956 unless ($self->{id}) {
957 $self->{id} = ..get..some..id..;
958 $WIDGET{$self->{id}} = $self;
959 }
960
961 { __widget__ => $self->{id} }
962 }
963
964
965=head2 shrink
966
967 $json = $json->shrink([$enable])
968
969 $enabled = $json->get_shrink
970
971With JSON::XS, this flag resizes strings generated by either
972C<encode> or C<decode> to their minimum size possible. This can save
973memory when your JSON texts are either very very long or you have many
974short strings. It will also try to downgrade any strings to octet-form
975if possible: perl stores strings internally either in an encoding called
976UTF-X or in octet-form. The latter cannot store everything but uses less
977space in general (and some buggy Perl or C code might even rely on that
978internal representation being used).
979
980With JSON::PP, it is noop about resizing strings but tries
981C<utf8::downgrade> to the returned string by C<encode>. See to L<utf8>.
982
983See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> and L<JSON::PP/METHODS>.
984
985=head2 max_depth
986
987 $json = $json->max_depth([$maximum_nesting_depth])
988
989 $max_depth = $json->get_max_depth
990
991Sets the maximum nesting level (default C<512>) accepted while encoding
992or decoding. If a higher nesting level is detected in JSON text or a Perl
993data structure, then the encoder and decoder will stop and croak at that
994point.
995
996Nesting level is defined by number of hash- or arrayrefs that the encoder
997needs to traverse to reach a given point or the number of C<{> or C<[>
998characters without their matching closing parenthesis crossed to reach a
999given character in a string.
1000
1001If no argument is given, the highest possible setting will be used, which
1002is rarely useful.
1003
1004Note that nesting is implemented by recursion in C. The default value has
1005been chosen to be as large as typical operating systems allow without
1006crashing. (JSON::XS)
1007
1008With JSON::PP as the backend, when a large value (100 or more) was set and
1009it de/encodes a deep nested object/text, it may raise a warning
1010'Deep recursion on subroutine' at the perl runtime phase.
1011
1012See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
1013
1014=head2 max_size
1015
1016 $json = $json->max_size([$maximum_string_size])
1017
1018 $max_size = $json->get_max_size
1019
1020Set the maximum length a JSON text may have (in bytes) where decoding is
1021being attempted. The default is C<0>, meaning no limit. When C<decode>
1022is called on a string that is longer then this many bytes, it will not
1023attempt to decode the string but throw an exception. This setting has no
1024effect on C<encode> (yet).
1025
1026If no argument is given, the limit check will be deactivated (same as when
1027C<0> is specified).
1028
1029See L<JSON::XS/SECURITY CONSIDERATIONS>, below, for more info on why this is useful.
1030
1031=head2 encode
1032
1033 $json_text = $json->encode($perl_scalar)
1034
1035Converts the given Perl data structure (a simple scalar or a reference
1036to a hash or array) to its JSON representation. Simple scalars will be
1037converted into JSON string or number sequences, while references to arrays
1038become JSON arrays and references to hashes become JSON objects. Undefined
1039Perl values (e.g. C<undef>) become JSON C<null> values.
1040References to the integers C<0> and C<1> are converted into C<true> and C<false>.
1041
1042=head2 decode
1043
1044 $perl_scalar = $json->decode($json_text)
1045
1046The opposite of C<encode>: expects a JSON text and tries to parse it,
1047returning the resulting simple scalar or reference. Croaks on error.
1048
1049JSON numbers and strings become simple Perl scalars. JSON arrays become
1050Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
1051C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
1052C<null> becomes C<undef>.
1053
1054=head2 decode_prefix
1055
1056 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
1057
1058This works like the C<decode> method, but instead of raising an exception
1059when there is trailing garbage after the first JSON object, it will
1060silently stop parsing there and return the number of characters consumed
1061so far.
1062
1063 JSON->new->decode_prefix ("[1] the tail")
1064 => ([], 3)
1065
1066See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
1067
1068=head2 property
1069
1070 $boolean = $json->property($property_name)
1071
1072Returns a boolean value about above some properties.
1073
1074The available properties are C<ascii>, C<latin1>, C<utf8>,
1075C<indent>,C<space_before>, C<space_after>, C<relaxed>, C<canonical>,
1076C<allow_nonref>, C<allow_unknown>, C<allow_blessed>, C<convert_blessed>,
1077C<shrink>, C<max_depth> and C<max_size>.
1078
1079 $boolean = $json->property('utf8');
1080 => 0
1081 $json->utf8;
1082 $boolean = $json->property('utf8');
1083 => 1
1084
1085Sets the property with a given boolean value.
1086
1087 $json = $json->property($property_name => $boolean);
1088
1089With no argument, it returns all the above properties as a hash reference.
1090
1091 $flag_hashref = $json->property();
1092
1093=head1 INCREMENTAL PARSING
1094
1095Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
1096
1097In some cases, there is the need for incremental parsing of JSON texts.
1098This module does allow you to parse a JSON stream incrementally.
1099It does so by accumulating text until it has a full JSON object, which
1100it then can decode. This process is similar to using C<decode_prefix>
1101to see if a full JSON object is available, but is much more efficient
1102(and can be implemented with a minimum of method calls).
1103
1104The backend module will only attempt to parse the JSON text once it is sure it
1105has enough text to get a decisive result, using a very simple but
1106truly incremental parser. This means that it sometimes won't stop as
1107early as the full parser, for example, it doesn't detect parenthesis
1108mismatches. The only thing it guarantees is that it starts decoding as
1109soon as a syntactically valid JSON text has been seen. This means you need
1110to set resource limits (e.g. C<max_size>) to ensure the parser will stop
1111parsing in the presence if syntax errors.
1112
1113The following methods implement this incremental parser.
1114
1115=head2 incr_parse
1116
1117 $json->incr_parse( [$string] ) # void context
1118
1119 $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
1120
1121 @obj_or_empty = $json->incr_parse( [$string] ) # list context
1122
1123This is the central parsing function. It can both append new text and
1124extract objects from the stream accumulated so far (both of these
1125functions are optional).
1126
1127If C<$string> is given, then this string is appended to the already
1128existing JSON fragment stored in the C<$json> object.
1129
1130After that, if the function is called in void context, it will simply
1131return without doing anything further. This can be used to add more text
1132in as many chunks as you want.
1133
1134If the method is called in scalar context, then it will try to extract
1135exactly I<one> JSON object. If that is successful, it will return this
1136object, otherwise it will return C<undef>. If there is a parse error,
1137this method will croak just as C<decode> would do (one can then use
1138C<incr_skip> to skip the erroneous part). This is the most common way of
1139using the method.
1140
1141And finally, in list context, it will try to extract as many objects
1142from the stream as it can find and return them, or the empty list
1143otherwise. For this to work, there must be no separators between the JSON
1144objects or arrays, instead they must be concatenated back-to-back. If
1145an error occurs, an exception will be raised as in the scalar context
1146case. Note that in this case, any previously-parsed JSON texts will be
1147lost.
1148
1149Example: Parse some JSON arrays/objects in a given string and return them.
1150
1151 my @objs = JSON->new->incr_parse ("[5][7][1,2]");
1152
1153=head2 incr_text
1154
1155 $lvalue_string = $json->incr_text
1156
1157This method returns the currently stored JSON fragment as an lvalue, that
1158is, you can manipulate it. This I<only> works when a preceding call to
1159C<incr_parse> in I<scalar context> successfully returned an object. Under
1160all other circumstances you must not call this function (I mean it.
1161although in simple tests it might actually work, it I<will> fail under
1162real world conditions). As a special exception, you can also call this
1163method before having parsed anything.
1164
1165This function is useful in two cases: a) finding the trailing text after a
1166JSON object or b) parsing multiple JSON objects separated by non-JSON text
1167(such as commas).
1168
1169 $json->incr_text =~ s/\s*,\s*//;
1170
1171In Perl 5.005, C<lvalue> attribute is not available.
1172You must write codes like the below:
1173
1174 $string = $json->incr_text;
1175 $string =~ s/\s*,\s*//;
1176 $json->incr_text( $string );
1177
1178=head2 incr_skip
1179
1180 $json->incr_skip
1181
1182This will reset the state of the incremental parser and will remove the
1183parsed text from the input buffer. This is useful after C<incr_parse>
1184died, in which case the input buffer and incremental parser state is left
1185unchanged, to skip the text parsed so far and to reset the parse state.
1186
1187=head2 incr_reset
1188
1189 $json->incr_reset
1190
1191This completely resets the incremental parser, that is, after this call,
1192it will be as if the parser had never parsed anything.
1193
1194This is useful if you want to repeatedly parse JSON objects and want to
1195ignore any trailing data, which means you have to reset the parser after
1196each successful decode.
1197
1198See to L<JSON::XS/INCREMENTAL PARSING> for examples.
1199
1200
1201=head1 JSON::PP SUPPORT METHODS
1202
1203The below methods are JSON::PP own methods, so when C<JSON> works
1204with JSON::PP (i.e. the created object is a JSON::PP object), available.
1205See to L<JSON::PP/JSON::PP OWN METHODS> in detail.
1206
1207If you use C<JSON> with additional C<-support_by_pp>, some methods
1208are available even with JSON::XS. See to L<USE PP FEATURES EVEN THOUGH XS BACKEND>.
1209
1210 BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
1211
1212 use JSON -support_by_pp;
1213
1214 my $json = JSON->new;
1215 $json->allow_nonref->escape_slash->encode("/");
1216
1217 # functional interfaces too.
1218 print to_json(["/"], {escape_slash => 1});
1219 print from_json('["foo"]', {utf8 => 1});
1220
1221If you do not want to all functions but C<-support_by_pp>,
1222use C<-no_export>.
1223
1224 use JSON -support_by_pp, -no_export;
1225 # functional interfaces are not exported.
1226
1227=head2 allow_singlequote
1228
1229 $json = $json->allow_singlequote([$enable])
1230
1231If C<$enable> is true (or missing), then C<decode> will accept
1232any JSON strings quoted by single quotations that are invalid JSON
1233format.
1234
1235 $json->allow_singlequote->decode({"foo":'bar'});
1236 $json->allow_singlequote->decode({'foo':"bar"});
1237 $json->allow_singlequote->decode({'foo':'bar'});
1238
1239As same as the C<relaxed> option, this option may be used to parse
1240application-specific files written by humans.
1241
1242=head2 allow_barekey
1243
1244 $json = $json->allow_barekey([$enable])
1245
1246If C<$enable> is true (or missing), then C<decode> will accept
1247bare keys of JSON object that are invalid JSON format.
1248
1249As same as the C<relaxed> option, this option may be used to parse
1250application-specific files written by humans.
1251
1252 $json->allow_barekey->decode('{foo:"bar"}');
1253
1254=head2 allow_bignum
1255
1256 $json = $json->allow_bignum([$enable])
1257
1258If C<$enable> is true (or missing), then C<decode> will convert
1259the big integer Perl cannot handle as integer into a L<Math::BigInt>
1260object and convert a floating number (any) into a L<Math::BigFloat>.
1261
1262On the contrary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
1263objects into JSON numbers with C<allow_blessed> enable.
1264
1265 $json->allow_nonref->allow_blessed->allow_bignum;
1266 $bigfloat = $json->decode('2.000000000000000000000000001');
1267 print $json->encode($bigfloat);
1268 # => 2.000000000000000000000000001
1269
1270See to L<MAPPING> about the conversion of JSON number.
1271
1272=head2 loose
1273
1274 $json = $json->loose([$enable])
1275
1276The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
1277and the module doesn't allow to C<decode> to these (except for \x2f).
1278If C<$enable> is true (or missing), then C<decode> will accept these
1279unescaped strings.
1280
1281 $json->loose->decode(qq|["abc
1282 def"]|);
1283
1284See to L<JSON::PP/JSON::PP OWN METHODS>.
1285
1286=head2 escape_slash
1287
1288 $json = $json->escape_slash([$enable])
1289
1290According to JSON Grammar, I<slash> (U+002F) is escaped. But by default
1291JSON backend modules encode strings without escaping slash.
1292
1293If C<$enable> is true (or missing), then C<encode> will escape slashes.
1294
1295=head2 indent_length
1296
1297 $json = $json->indent_length($length)
1298
1299With JSON::XS, The indent space length is 3 and cannot be changed.
1300With JSON::PP, it sets the indent space length with the given $length.
1301The default is 3. The acceptable range is 0 to 15.
1302
1303=head2 sort_by
1304
1305 $json = $json->sort_by($function_name)
1306 $json = $json->sort_by($subroutine_ref)
1307
1308If $function_name or $subroutine_ref are set, its sort routine are used.
1309
1310 $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
1311 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
1312
1313 $js = $pc->sort_by('own_sort')->encode($obj);
1314 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
1315
1316 sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
1317
1318As the sorting routine runs in the JSON::PP scope, the given
1319subroutine name and the special variables C<$a>, C<$b> will begin
1320with 'JSON::PP::'.
1321
1322If $integer is set, then the effect is same as C<canonical> on.
1323
1324See to L<JSON::PP/JSON::PP OWN METHODS>.
1325
1326=head1 MAPPING
1327
1328This section is copied from JSON::XS and modified to C<JSON>.
1329JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
1330
1331See to L<JSON::XS/MAPPING>.
1332
1333=head2 JSON -> PERL
1334
1335=over 4
1336
1337=item object
1338
1339A JSON object becomes a reference to a hash in Perl. No ordering of object
1340keys is preserved (JSON does not preserver object key ordering itself).
1341
1342=item array
1343
1344A JSON array becomes a reference to an array in Perl.
1345
1346=item string
1347
1348A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
1349are represented by the same codepoints in the Perl string, so no manual
1350decoding is necessary.
1351
1352=item number
1353
1354A JSON number becomes either an integer, numeric (floating point) or
1355string scalar in perl, depending on its range and any fractional parts. On
1356the Perl level, there is no difference between those as Perl handles all
1357the conversion details, but an integer may take slightly less memory and
1358might represent more values exactly than floating point numbers.
1359
1360If the number consists of digits only, C<JSON> will try to represent
1361it as an integer value. If that fails, it will try to represent it as
1362a numeric (floating point) value if that is possible without loss of
1363precision. Otherwise it will preserve the number as a string value (in
1364which case you lose roundtripping ability, as the JSON number will be
1365re-encoded to a JSON string).
1366
1367Numbers containing a fractional or exponential part will always be
1368represented as numeric (floating point) values, possibly at a loss of
1369precision (in which case you might lose perfect roundtripping ability, but
1370the JSON number will still be re-encoded as a JSON number).
1371
1372Note that precision is not accuracy - binary floating point values cannot
1373represent most decimal fractions exactly, and when converting from and to
1374floating point, C<JSON> only guarantees precision up to but not including
1375the least significant bit.
1376
1377If the backend is JSON::PP and C<allow_bignum> is enable, the big integers
1378and the numeric can be optionally converted into L<Math::BigInt> and
1379L<Math::BigFloat> objects.
1380
1381=item true, false
1382
1383These JSON atoms become C<JSON::true> and C<JSON::false>,
1384respectively. They are overloaded to act almost exactly like the numbers
1385C<1> and C<0>. You can check whether a scalar is a JSON boolean by using
1386the C<JSON::is_bool> function.
1387
1388If C<JSON::true> and C<JSON::false> are used as strings or compared as strings,
1389they represent as C<true> and C<false> respectively.
1390
1391 print JSON::true . "\n";
1392 => true
1393 print JSON::true + 1;
1394 => 1
1395
1396 ok(JSON::true eq 'true');
1397 ok(JSON::true eq '1');
1398 ok(JSON::true == 1);
1399
1400C<JSON> will install these missing overloading features to the backend modules.
1401
1402
1403=item null
1404
1405A JSON null atom becomes C<undef> in Perl.
1406
1407C<JSON::null> returns C<undef>.
1408
1409=back
1410
1411
1412=head2 PERL -> JSON
1413
1414The mapping from Perl to JSON is slightly more difficult, as Perl is a
1415truly typeless language, so we can only guess which JSON type is meant by
1416a Perl value.
1417
1418=over 4
1419
1420=item hash references
1421
1422Perl hash references become JSON objects. As there is no inherent ordering
1423in hash keys (or JSON objects), they will usually be encoded in a
1424pseudo-random order that can change between runs of the same program but
1425stays generally the same within a single run of a program. C<JSON>
1426optionally sort the hash keys (determined by the I<canonical> flag), so
1427the same data structure will serialise to the same JSON text (given same
1428settings and version of JSON::XS), but this incurs a runtime overhead
1429and is only rarely useful, e.g. when you want to compare some JSON text
1430against another for equality.
1431
1432In future, the ordered object feature will be added to JSON::PP using C<tie> mechanism.
1433
1434
1435=item array references
1436
1437Perl array references become JSON arrays.
1438
1439=item other references
1440
1441Other unblessed references are generally not allowed and will cause an
1442exception to be thrown, except for references to the integers C<0> and
1443C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
1444also use C<JSON::false> and C<JSON::true> to improve readability.
1445
1446 to_json [\0,JSON::true] # yields [false,true]
1447
1448=item JSON::true, JSON::false, JSON::null
1449
1450These special values become JSON true and JSON false values,
1451respectively. You can also use C<\1> and C<\0> directly if you want.
1452
1453JSON::null returns C<undef>.
1454
1455=item blessed objects
1456
1457Blessed objects are not directly representable in JSON. See the
1458C<allow_blessed> and C<convert_blessed> methods on various options on
1459how to deal with this: basically, you can choose between throwing an
1460exception, encoding the reference as if it weren't blessed, or provide
1461your own serialiser method.
1462
1463With C<convert_blessed_universally> mode, C<encode> converts blessed
1464hash references or blessed array references (contains other blessed references)
1465into JSON members and arrays.
1466
1467 use JSON -convert_blessed_universally;
1468 JSON->new->allow_blessed->convert_blessed->encode( $blessed_object );
1469
1470See to L<convert_blessed>.
1471
1472=item simple scalars
1473
1474Simple Perl scalars (any scalar that is not a reference) are the most
1475difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
1476JSON C<null> values, scalars that have last been used in a string context
1477before encoding as JSON strings, and anything else as number value:
1478
1479 # dump as number
1480 encode_json [2] # yields [2]
1481 encode_json [-3.0e17] # yields [-3e+17]
1482 my $value = 5; encode_json [$value] # yields [5]
1483
1484 # used as string, so dump as string
1485 print $value;
1486 encode_json [$value] # yields ["5"]
1487
1488 # undef becomes null
1489 encode_json [undef] # yields [null]
1490
1491You can force the type to be a string by stringifying it:
1492
1493 my $x = 3.1; # some variable containing a number
1494 "$x"; # stringified
1495 $x .= ""; # another, more awkward way to stringify
1496 print $x; # perl does it for you, too, quite often
1497
1498You can force the type to be a number by numifying it:
1499
1500 my $x = "3"; # some variable containing a string
1501 $x += 0; # numify it, ensuring it will be dumped as a number
1502 $x *= 1; # same thing, the choice is yours.
1503
1504You can not currently force the type in other, less obscure, ways.
1505
1506Note that numerical precision has the same meaning as under Perl (so
1507binary to decimal conversion follows the same rules as in Perl, which
1508can differ to other languages). Also, your perl interpreter might expose
1509extensions to the floating point numbers of your platform, such as
1510infinities or NaN's - these cannot be represented in JSON, and it is an
1511error to pass those in.
1512
1513=item Big Number
1514
1515If the backend is JSON::PP and C<allow_bignum> is enable,
1516C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
1517objects into JSON numbers.
1518
1519
1520=back
1521
1522=head1 JSON and ECMAscript
1523
1524See to L<JSON::XS/JSON and ECMAscript>.
1525
1526=head1 JSON and YAML
1527
1528JSON is not a subset of YAML.
1529See to L<JSON::XS/JSON and YAML>.
1530
1531
1532=head1 BACKEND MODULE DECISION
1533
1534When you use C<JSON>, C<JSON> tries to C<use> JSON::XS. If this call failed, it will
1535C<uses> JSON::PP. The required JSON::XS version is I<2.2> or later.
1536
1537The C<JSON> constructor method returns an object inherited from the backend module,
1538and JSON::XS object is a blessed scalar reference while JSON::PP is a blessed hash
1539reference.
1540
1541So, your program should not depend on the backend module, especially
1542returned objects should not be modified.
1543
1544 my $json = JSON->new; # XS or PP?
1545 $json->{stash} = 'this is xs object'; # this code may raise an error!
1546
1547To check the backend module, there are some methods - C<backend>, C<is_pp> and C<is_xs>.
1548
1549 JSON->backend; # 'JSON::XS' or 'JSON::PP'
1550
1551 JSON->backend->is_pp: # 0 or 1
1552
1553 JSON->backend->is_xs: # 1 or 0
1554
1555 $json->is_xs; # 1 or 0
1556
1557 $json->is_pp; # 0 or 1
1558
1559
1560If you set an environment variable C<PERL_JSON_BACKEND>, the calling action will be changed.
1561
1562=over
1563
1564=item PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP'
1565
1566Always use JSON::PP
1567
1568=item PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP'
1569
1570(The default) Use compiled JSON::XS if it is properly compiled & installed,
1571otherwise use JSON::PP.
1572
1573=item PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS'
1574
1575Always use compiled JSON::XS, die if it isn't properly compiled & installed.
1576
1577=item PERL_JSON_BACKEND = 'JSON::backportPP'
1578
1579Always use JSON::backportPP.
1580JSON::backportPP is JSON::PP back port module.
1581C<JSON> includes JSON::backportPP instead of JSON::PP.
1582
1583=back
1584
1585These ideas come from L<DBI::PurePerl> mechanism.
1586
1587example:
1588
1589 BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' }
1590 use JSON; # always uses JSON::PP
1591
1592In future, it may be able to specify another module.
1593
1594=head1 USE PP FEATURES EVEN THOUGH XS BACKEND
1595
1596Many methods are available with either JSON::XS or JSON::PP and
1597when the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS unsupported)
1598method is called, it will C<warn> and be noop.
1599
1600But If you C<use> C<JSON> passing the optional string C<-support_by_pp>,
1601it makes a part of those unsupported methods available.
1602This feature is achieved by using JSON::PP in C<de/encode>.
1603
1604 BEGIN { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS
1605 use JSON -support_by_pp;
1606 my $json = JSON->new;
1607 $json->allow_nonref->escape_slash->encode("/");
1608
1609At this time, the returned object is a C<JSON::Backend::XS::Supportable>
1610object (re-blessed XS object), and by checking JSON::XS unsupported flags
1611in de/encoding, can support some unsupported methods - C<loose>, C<allow_bignum>,
1612C<allow_barekey>, C<allow_singlequote>, C<escape_slash> and C<indent_length>.
1613
1614When any unsupported methods are not enable, C<XS de/encode> will be
1615used as is. The switch is achieved by changing the symbolic tables.
1616
1617C<-support_by_pp> is effective only when the backend module is JSON::XS
1618and it makes the de/encoding speed down a bit.
1619
1620See to L<JSON::PP SUPPORT METHODS>.
1621
1622=head1 INCOMPATIBLE CHANGES TO OLD VERSION
1623
1624There are big incompatibility between new version (2.00) and old (1.xx).
1625If you use old C<JSON> 1.xx in your code, please check it.
1626
1627See to L<Transition ways from 1.xx to 2.xx.>
1628
1629=over
1630
1631=item jsonToObj and objToJson are obsoleted.
1632
1633Non Perl-style name C<jsonToObj> and C<objToJson> are obsoleted
1634(but not yet deleted from the source).
1635If you use these functions in your code, please replace them
1636with C<from_json> and C<to_json>.
1637
1638
1639=item Global variables are no longer available.
1640
1641C<JSON> class variables - C<$JSON::AUTOCONVERT>, C<$JSON::BareKey>, etc...
1642- are not available any longer.
1643Instead, various features can be used through object methods.
1644
1645
1646=item Package JSON::Converter and JSON::Parser are deleted.
1647
1648Now C<JSON> bundles with JSON::PP which can handle JSON more properly than them.
1649
1650=item Package JSON::NotString is deleted.
1651
1652There was C<JSON::NotString> class which represents JSON value C<true>, C<false>, C<null>
1653and numbers. It was deleted and replaced by C<JSON::Boolean>.
1654
1655C<JSON::Boolean> represents C<true> and C<false>.
1656
1657C<JSON::Boolean> does not represent C<null>.
1658
1659C<JSON::null> returns C<undef>.
1660
1661C<JSON> makes L<JSON::XS::Boolean> and L<JSON::PP::Boolean> is-a relation
1662to L<JSON::Boolean>.
1663
1664=item function JSON::Number is obsoleted.
1665
1666C<JSON::Number> is now needless because JSON::XS and JSON::PP have
1667round-trip integrity.
1668
1669=item JSONRPC modules are deleted.
1670
1671Perl implementation of JSON-RPC protocol - C<JSONRPC >, C<JSONRPC::Transport::HTTP>
1672and C<Apache::JSONRPC > are deleted in this distribution.
1673Instead of them, there is L<JSON::RPC> which supports JSON-RPC protocol version 1.1.
1674
1675=back
1676
1677=head2 Transition ways from 1.xx to 2.xx.
1678
1679You should set C<suport_by_pp> mode firstly, because
1680it is always successful for the below codes even with JSON::XS.
1681
1682 use JSON -support_by_pp;
1683
1684=over
1685
1686=item Exported jsonToObj (simple)
1687
1688 from_json($json_text);
1689
1690=item Exported objToJson (simple)
1691
1692 to_json($perl_scalar);
1693
1694=item Exported jsonToObj (advanced)
1695
1696 $flags = {allow_barekey => 1, allow_singlequote => 1};
1697 from_json($json_text, $flags);
1698
1699equivalent to:
1700
1701 $JSON::BareKey = 1;
1702 $JSON::QuotApos = 1;
1703 jsonToObj($json_text);
1704
1705=item Exported objToJson (advanced)
1706
1707 $flags = {allow_blessed => 1, allow_barekey => 1};
1708 to_json($perl_scalar, $flags);
1709
1710equivalent to:
1711
1712 $JSON::BareKey = 1;
1713 objToJson($perl_scalar);
1714
1715=item jsonToObj as object method
1716
1717 $json->decode($json_text);
1718
1719=item objToJson as object method
1720
1721 $json->encode($perl_scalar);
1722
1723=item new method with parameters
1724
1725The C<new> method in 2.x takes any parameters no longer.
1726You can set parameters instead;
1727
1728 $json = JSON->new->pretty;
1729
1730=item $JSON::Pretty, $JSON::Indent, $JSON::Delimiter
1731
1732If C<indent> is enable, that means C<$JSON::Pretty> flag set. And
1733C<$JSON::Delimiter> was substituted by C<space_before> and C<space_after>.
1734In conclusion:
1735
1736 $json->indent->space_before->space_after;
1737
1738Equivalent to:
1739
1740 $json->pretty;
1741
1742To change indent length, use C<indent_length>.
1743
1744(Only with JSON::PP, if C<-support_by_pp> is not used.)
1745
1746 $json->pretty->indent_length(2)->encode($perl_scalar);
1747
1748=item $JSON::BareKey
1749
1750(Only with JSON::PP, if C<-support_by_pp> is not used.)
1751
1752 $json->allow_barekey->decode($json_text)
1753
1754=item $JSON::ConvBlessed
1755
1756use C<-convert_blessed_universally>. See to L<convert_blessed>.
1757
1758=item $JSON::QuotApos
1759
1760(Only with JSON::PP, if C<-support_by_pp> is not used.)
1761
1762 $json->allow_singlequote->decode($json_text)
1763
1764=item $JSON::SingleQuote
1765
1766Disable. C<JSON> does not make such a invalid JSON string any longer.
1767
1768=item $JSON::KeySort
1769
1770 $json->canonical->encode($perl_scalar)
1771
1772This is the ascii sort.
1773
1774If you want to use with your own sort routine, check the C<sort_by> method.
1775
1776(Only with JSON::PP, even if C<-support_by_pp> is used currently.)
1777
1778 $json->sort_by($sort_routine_ref)->encode($perl_scalar)
1779
1780 $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar)
1781
1782Can't access C<$a> and C<$b> but C<$JSON::PP::a> and C<$JSON::PP::b>.
1783
1784=item $JSON::SkipInvalid
1785
1786 $json->allow_unknown
1787
1788=item $JSON::AUTOCONVERT
1789
1790Needless. C<JSON> backend modules have the round-trip integrity.
1791
1792=item $JSON::UTF8
1793
1794Needless because C<JSON> (JSON::XS/JSON::PP) sets
1795the UTF8 flag on properly.
1796
1797 # With UTF8-flagged strings
1798
1799 $json->allow_nonref;
1800 $str = chr(1000); # UTF8-flagged
1801
1802 $json_text = $json->utf8(0)->encode($str);
1803 utf8::is_utf8($json_text);
1804 # true
1805 $json_text = $json->utf8(1)->encode($str);
1806 utf8::is_utf8($json_text);
1807 # false
1808
1809 $str = '"' . chr(1000) . '"'; # UTF8-flagged
1810
1811 $perl_scalar = $json->utf8(0)->decode($str);
1812 utf8::is_utf8($perl_scalar);
1813 # true
1814 $perl_scalar = $json->utf8(1)->decode($str);
1815 # died because of 'Wide character in subroutine'
1816
1817See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
1818
1819=item $JSON::UnMapping
1820
1821Disable. See to L<MAPPING>.
1822
1823=item $JSON::SelfConvert
1824
1825This option was deleted.
1826Instead of it, if a given blessed object has the C<TO_JSON> method,
1827C<TO_JSON> will be executed with C<convert_blessed>.
1828
1829 $json->convert_blessed->encode($blessed_hashref_or_arrayref)
1830 # if need, call allow_blessed
1831
1832Note that it was C<toJson> in old version, but now not C<toJson> but C<TO_JSON>.
1833
1834=back
1835
1836=head1 TODO
1837
1838=over
1839
1840=item example programs
1841
1842=back
1843
1844=head1 THREADS
1845
1846No test with JSON::PP. If with JSON::XS, See to L<JSON::XS/THREADS>.
1847
1848
1849=head1 BUGS
1850
1851Please report bugs relevant to C<JSON> to E<lt>makamaka[at]cpan.orgE<gt>.
1852
1853
1854=head1 SEE ALSO
1855
1856Most of the document is copied and modified from JSON::XS doc.
1857
1858L<JSON::XS>, L<JSON::PP>
1859
1860C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>)
1861
1862=head1 AUTHOR
1863
1864Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
1865
1866JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de>
1867
1868The release of this new version owes to the courtesy of Marc Lehmann.
1869
1870
1871=head1 COPYRIGHT AND LICENSE
1872
1873Copyright 2005-2013 by Makamaka Hannyaharamitu
1874
1875This library is free software; you can redistribute it and/or modify
1876it under the same terms as Perl itself.
1877
1878=cut
1879
1880
1881;